package org.sundatagroup.aurora.show.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.sundatagroup.aurora.core.entity.pojo.Module;
import org.sundatagroup.aurora.core.service.ModuleService;
import org.sundatagroup.aurora.show.service.SidDispatcher;

/**
 * 直接打开, 用于显示项目展示的网页. 该 Controller 里面的接口均为打开网页, 而非传输数据.
 * <br>这里将原来 {@link DisplayController} 的所有查找 Module 部分的接口移了出来.
 * @author Zdream
 * @date 2018-05-25
 * @since 0.2.0
 */
@RequestMapping("/aurora")
@Controller
public class ShowModuleController {
	
	@Autowired
	private ModuleService moduleService;

	@Autowired
	private SidDispatcher sidDispatcher;
	
	/**
	 * 打开 Module 页面
	 * 返回 displayType:module
	 */
	@RequestMapping("show/module/{mid}")
	public ModelAndView displayModule(@PathVariable int mid,
							   @RequestParam(required = false) String sid){
		ModelAndView mv = new ModelAndView("module");
		mv.addObject("displayType","module");
		sid = (sid == null) ? sidDispatcher.createSid() : sid;
		mv.addObject("sid",sid);
		mv.addObject("mid",mid);
		return mv;
	}

	/**
	 * 返回所有module的列表.项目过多时分页,默认一页10个
	 */
	@RequestMapping("show/module/index")
	public ModelAndView moduleIndex(@RequestParam(required = false)Integer start,
							   @RequestParam(required = false) Integer size){
		size = (size == null) ? 10 : size;
		start = (start == null) ? 0 : start;
		ModelAndView mv = new ModelAndView("moduleTest");

		List<Module> module = moduleService.queryByPage(start, size);
		List<Integer> moduleHref = new ArrayList<>();

		int moduleNum = moduleService.countModules();
		int pageCounter = moduleNum / size;
		if ((pageCounter - size) % size > 0)
			pageCounter++;
		if (moduleNum <= size)
			pageCounter--;// 只要1页不显示页码

		for (int i = 0; i < pageCounter; i++) {
			moduleHref.add(i + 1);
		}

		String sid = sidDispatcher.createSid();

		mv.addObject("module", module);
		mv.addObject("moduleHref", moduleHref);
		mv.addObject("sid", sid);
		mv.addObject("pageCounter", pageCounter);
		mv.addObject("size", size);

		return mv;
	}
}
